package jia.game;

//~--- non-JDK imports --------------------------------------------------------
import jia.core.GameStateManager;
import jia.game.GenericFlags;
import org.apache.log4j.Logger;

//~--- JDK imports ------------------------------------------------------------
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

public abstract class AbstractViewport extends Viewport {
    private static final Logger log = Logger.getLogger(AbstractViewport.class);
    protected Insets borderInsets = new Insets(0, 0, 0, 0);
    protected GameStateManager gameState;
    protected BufferedImage skinImage;
    
    public AbstractViewport() {
        // GNDN
    }
    
    public void setSkinBorderInset(Insets inset) {
        borderInsets = inset;
        
        Dimension size = getSize();
        
        if (GenericFlags.debugMessages) {
            log.debug("Base size was " + size.getWidth() + "x" + size.getHeight());
        }
        
        size.setSize(size.getWidth() + borderInsets.left + borderInsets.right,
            size.getHeight() + borderInsets.top + borderInsets.bottom);
        
        setSize(size);
        
        if (GenericFlags.debugMessages) {
            log.debug("Set size to " + size.getWidth() + "x" + size.getHeight());
        }
    }
    
    public void setSkinImage(String resource) {
        URL skinImageFileUrl = getClass().getClassLoader().getResource(resource);
        
        try {
            skinImage = ImageIO.read(skinImageFileUrl);
            
            if (skinImage == null) {
                if (GenericFlags.warningMessages) {
                    if (GenericFlags.warningMessages) {
                        log.warn("Couldn't load skin resource -- non-exception");
                    }
                }
            }
            
            if (GenericFlags.debugMessages) {
                log.debug("Image is " + skinImage.getWidth() + "x" + skinImage.getHeight());
            }
        } catch (IOException e) {
            if (GenericFlags.errorMessages) {
                log.error("Couldn't load skin resource '" + resource + "' -- using blank");
            }
        }
    }
    
    public void updateGameState(GameStateManager gameState) {
        this.gameState = gameState;
        repaint();
    }
    
    protected abstract void renderView(Graphics2D g);
    
    protected void paintComponent(Graphics graphics) {
        Graphics2D g2 = (Graphics2D) graphics;
        
        renderView(g2);
        
        if (skinImage != null) {
            g2.drawImage(skinImage, 0, 0, this);
        }
    }
    
    /**
     * Setting a tileable skin on a viewport is a little pointless, as there needs
     * to be a transparent hole in the middle for the rendered view to show
     * through. As such, this method does nothing.
     */
    public void setSkinTileable(boolean tileable) {
        // do nothing
    }
}
